package com.zhang.family_doctor.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhang.family_doctor.dto.DoctorDto;
import com.zhang.family_doctor.dto.DoctorRoleDto;
import com.zhang.family_doctor.entity.Doctor;
import com.zhang.family_doctor.entity.DoctorRole;
import com.zhang.family_doctor.entity.R;
import com.zhang.family_doctor.mapper.DoctorMapper;
import com.zhang.family_doctor.mapper.RoleMapper;
import com.zhang.family_doctor.mapper.TeamMapper;
import com.zhang.family_doctor.service.DoctorService;
import com.zhang.family_doctor.utils.CommonUtils;
import com.zhang.family_doctor.utils.TokenUtils;
import com.zhang.family_doctor.vo.DoctorAllVO;
import com.zhang.family_doctor.vo.DoctorTeamVO;
import com.zhang.family_doctor.vo.DoctorVO;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class DoctorServiceImpl implements DoctorService {

    @Autowired
    private DoctorMapper doctorMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private TeamMapper teamMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 后台管理登录
     *
     * @param phone
     * @param password
     * @return
     */
    @Override
    public R login(String phone, String password) {

        Map<String, Object> map = new HashMap();
        Doctor doctorVO = doctorMapper.getDoctorByPhone(phone);
        if (doctorVO == null) {
            map.put("tokenBackstage:", null);
            map.put("msg:", "用户不存在！或给禁用了");
            return R.success(map);
        }
        String pwd = doctorVO.getPassword();
        if (!pwd.equals(password)) {
            map.put("tokenBackstage:", null);
            map.put("msg:", "密码错误！");
            return R.success(map);
        }
        String tokenBackstage = TokenUtils.signBackstage(doctorVO);
        map.put("tokenBackstage:", tokenBackstage);
        //将我们生成的token保存在Redis中，并且设置有效期为6小时
        redisTemplate.opsForValue().set("tokenBackstage", tokenBackstage, 1 * 6 * 60, TimeUnit.MINUTES);
        return R.success(map);
    }

    /**
     * 给第三方回调接口拿token
     * @param phone
     * @param password
     * @return
     */
    @Override
    public String logins(String phone, String password) {

        Doctor doctorVO = doctorMapper.getDoctorByPhone(phone);

        String tokenBackstage = TokenUtils.signBackstage(doctorVO);

        return tokenBackstage;
    }

    /**
     * 新增医生
     *
     * @param doctorRoleDto
     * @param request
     * @return
     */
    @Override
    @Transactional //事务
    public R saveDoctor(DoctorRoleDto doctorRoleDto, HttpServletRequest request) {

        int id = CommonUtils.genUUID();
        //从token中拿登录人名称
        String tokenBackstage = request.getHeader("tokenBackstage");
        String getName = TokenUtils.verifyAndGetName(tokenBackstage);
        //截取和拼接number
        String s = DateFormatUtils.format(new Date(), "yyyyMMdd");
        List<String> doctorByNumber = doctorMapper.getDoctorByNumber(s);
        if (doctorByNumber.size() != 0) {
            List<Integer> arrayList = new ArrayList();
            for (String str : doctorByNumber) {
                arrayList.add(Integer.valueOf(str.substring(8, str.length())));
            }
            Integer max = Collections.max(arrayList);
            int i = max + 1;
            String format = String.format("%03d", i);
            String number = s + format;
            //设置默认的
            int state = 1;
            String phone = doctorRoleDto.getPhone();
            //校验手机号
            String regex = "^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$";
            Pattern compile = Pattern.compile(regex);
            Matcher matcher = compile.matcher(phone);
            boolean matches = matcher.matches();
            if (matches) {
                Doctor doctorByPhone = doctorMapper.getDoctorByPhone(phone);
                if (doctorByPhone != null) {
                    return R.buildFailure("该手机号已经注册！请换一个手机号！");
                }
                doctorRoleDto.setId(id);
                doctorRoleDto.setNumber(number);
                //默认启用
                doctorRoleDto.setState(state);
                doctorRoleDto.setFounder(getName);
                doctorRoleDto.setCreateTime(new Date());
                doctorRoleDto.setUpdateTime(new Date());
                doctorMapper.saveDoctor(doctorRoleDto);
                List<DoctorRole> doctorRoleList = doctorRoleDto.getDoctorRoleList();
                for (DoctorRole doctorRole : doctorRoleList) {
                    doctorRole.setId(CommonUtils.genUUID());
                    doctorRole.setDoctorId(id);
                }
                doctorMapper.saveAll(doctorRoleList);
                return R.success("新增医生成功！");
            } else {
                return R.buildFailure("手机号格式不对,请输入有效的手机号！");
            }
        } else {
            int i = 1;
            String format = String.format("%03d", i);
            String number = s + format;
            //设置默认的
            int state = 1;
            String phone = doctorRoleDto.getPhone();
            //校验手机号
            String regex = "^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$";
            Pattern compile = Pattern.compile(regex);
            Matcher matcher = compile.matcher(phone);
            boolean matches = matcher.matches();
            if (matches) {
                Doctor doctorByPhone = doctorMapper.getDoctorByPhone(phone);
                if (doctorByPhone != null) {
                    return R.buildFailure("该手机号已经注册！请换一个手机号！");
                }
                doctorRoleDto.setId(id);
                doctorRoleDto.setNumber(number);
                //默认启用
                doctorRoleDto.setState(state);
                doctorRoleDto.setFounder(getName);
                doctorRoleDto.setCreateTime(new Date());
                doctorRoleDto.setUpdateTime(new Date());
                doctorMapper.saveDoctor(doctorRoleDto);

                List<DoctorRole> doctorRoleList = doctorRoleDto.getDoctorRoleList();
                for (DoctorRole doctorRole : doctorRoleList) {

                    doctorRole.setId(CommonUtils.genUUID());
                    doctorRole.setDoctorId(id);
                }
                doctorMapper.saveAll(doctorRoleList);
                return R.success("新增医生成功！");
            } else {
                return R.buildFailure("手机号格式不对,请输入有效的手机号！");
            }
        }
    }

    /**
     * 修改医生信息
     *
     * @param doctorRoleDto
     * @param request
     * @return
     */
    @Override
    @Transactional
    public R<String> updateDoctor(DoctorRoleDto doctorRoleDto, HttpServletRequest request) {

        String tokenBackstage = request.getHeader("tokenBackstage");
        String getName = TokenUtils.verifyAndGetName(tokenBackstage);
        String phone = doctorRoleDto.getPhone();
        Integer id = doctorRoleDto.getId();
        //校验手机号
        String regex = "^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$";
        Pattern compile = Pattern.compile(regex);
        if (phone != null) {
            Matcher matcher = compile.matcher(phone);
            boolean matches = matcher.matches();
            if (matches) {
                Doctor doctorByPhone = doctorMapper.getDoctorByPhone(phone);

                if (doctorByPhone != null) {
                    return R.buildFailure("该手机号已经绑定了医生，请重新输入一个手机号！");
                }
                doctorRoleDto.setUpdateTime(new Date());
                doctorRoleDto.setFounder(getName);
                doctorMapper.updateDoctorById(doctorRoleDto);

                //清空医生角色表再进行插入
                doctorMapper.deleteByDoctorId(id);

                List<DoctorRole> doctorRoleList = doctorRoleDto.getDoctorRoleList();

                for (DoctorRole doctorRole : doctorRoleList) {

                    doctorRole.setId(CommonUtils.genUUID());
                    doctorRole.setDoctorId(id);
                }
                doctorMapper.saveAll(doctorRoleList);
                return R.success("编辑成功！");
            } else {
                return R.buildFailure("手机号格式不对,请输入有效的手机号！");
            }
        } else {

            doctorRoleDto.setUpdateTime(new Date());
            doctorRoleDto.setFounder(getName);
            doctorMapper.updateDoctorById(doctorRoleDto);

            //清空医生角色表再进行插入
            doctorMapper.deleteByDoctorId(id);

            List<DoctorRole> doctorRoleList = doctorRoleDto.getDoctorRoleList();

            for (DoctorRole doctorRole : doctorRoleList) {

                doctorRole.setId(CommonUtils.genUUID());
                doctorRole.setDoctorId(id);
            }
            doctorMapper.saveAll(doctorRoleList);
            return R.success("编辑成功！");
        }
    }

    /**
     * 查询所有的医生
     * @return
     */
    @Override
    public R<PageInfo<DoctorAllVO>> getAllDoctor(DoctorDto doctorDto) {

        Integer pageNum = doctorDto.getPageNum();
        Integer pageSize = doctorDto.getPageSize();
        PageHelper.startPage(pageNum,pageSize);
        List<DoctorAllVO> allDoctor = doctorMapper.getAllDoctor(doctorDto);

        PageInfo<DoctorAllVO> pageInfo = new PageInfo<>(allDoctor);

        return R.success(pageInfo);
    }

    /**
     * 医生端登录
     *
     * @param phone
     * @param password
     * @return
     */
    @Override
    public R<Map> loginDoctor(String phone, String password) {

        Map<String, Object> map = new HashMap();
        Doctor doctorVO = doctorMapper.getDoctorByPhone(phone);
        if (doctorVO == null) {
            map.put("tokenDoctor:", null);
            map.put("msg:", "用户不存在！或给禁用了！");
            return R.success(map);
        }
        String pwd = doctorVO.getPassword();
        if (!pwd.equals(password)) {
            map.put("tokenDoctor:", null);
            map.put("msg:", "密码错误！");
            return R.success(map);
        }
        String tokenDoctor = TokenUtils.signDoctor(doctorVO);
        map.put("tokenDoctor:", tokenDoctor);
        //将我们生成的token保存在Redis中，并且设置有效期为6小时
        redisTemplate.opsForValue().set("tokenDoctor", tokenDoctor, 1 * 6 * 60, TimeUnit.MINUTES);
        return R.success(map);
    }

    /**
     * 根据医生id删除医生
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public R<String> deleteDoctor(Integer id) {

        //删除该医生下的所有角色再删除医生
        doctorMapper.deleteByDoctorId(id);
        doctorMapper.deleteDoctor(id);
        return R.success("删除成功！");

    }

    /**
     * 医生单个新增或多个新增角色
     *
     * @param doctorRoleList
     * @return
     */
    @Override
    public R<String> saveAll(List<DoctorRole> doctorRoleList) {

        for (DoctorRole doctorRole : doctorRoleList) {

            doctorRole.setId(CommonUtils.genUUID());

        }
        doctorMapper.saveAll(doctorRoleList);
        return R.success("新增成功！");
    }

    /**
     * 查看医生详情
     * @param id
     * @return
     */
    @Override
    public R<DoctorVO> getDoctorDetails(Integer id) {

        DoctorVO doctorVO = new DoctorVO();
        //查询出医生信息
        Doctor doctor = doctorMapper.selectDoctorById(id);
        //查询出医生角色名
        List<String> doctorRoleNameList = roleMapper.selectDoctorRoleName(id);
        //查询出机构名
        List<DoctorTeamVO> doctorTeamVOS = teamMapper.selectDoctorTeamVO(id);
        //查询出团队名

        doctorVO.setDoctor(doctor);
        doctorVO.setDoctorRoleNameList(doctorRoleNameList);
        doctorVO.setDoctorTeamVOList(doctorTeamVOS);

        return R.success(doctorVO);
    }




}
